<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <TitleSearch :show-before="true">
            <template v-slot:before>
              <el-button
                type="primary"
                style="float: left; margin-top: 10px"
                size="small"
                @click="addFn"
              >+ 添加分类</el-button>
            </template>
            <template v-slot:after>
              <el-input
                v-model="searchData"
                style="float: right; padding: 3px 0"
                placeholder="请输入内容"
                class="input-with-select"
              >
                <el-button slot="append" icon="el-icon-search" @click="searchFn" />
              </el-input>
            </template>
          </TitleSearch>
        </div>
        <!-- 添加分类 -->
        <!-- <div slot="header" class="clearfix">
          <el-button
            type="primary"
            style="float: left; margin-top: 10px"
            size="small"
            @click="addFn"
          >+ 添加分类</el-button>
          <el-input
            v-model="searchData"
            style="float: right; padding: 3px 0"
            placeholder="请输入内容"
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search" @click="searchFn" />
          </el-input>
        </div> -->
        <!-- 表格数据 -->
        <el-table :data="tableData" border style="width: 100%" height="500px">
          <el-table-column prop="image" label="图片" width="180">
            <template v-slot="{row}">
              <el-image
                style="width: 100px; height: 100px"
                :src="row.image"
                :fit="fit='scale-down'"
              />
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" width="180" />
          <el-table-column prop="desc" label="介绍" />
          <el-table-column label="操作" width="180">
            <template v-slot="{row}">
              <el-button type="primary" size="small" @click="editFn(row.id)">编辑</el-button>
              <el-button type="danger" size="small" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            :current-page="page"
            :page-count="pagecount"
            :page-size="pagesize"
            layout="total,prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
        <!-- 弹框 -->
        <el-dialog title="添加分类" :visible="isShowDialog" @close="closeFn">
          <el-form ref="formData" :model="form" :rules="rules">
            <el-form-item label="标题" label-width="120px" prop="title">
              <el-input v-model="form.title" autocomplete="off" />
            </el-form-item>
            <el-form-item label="描述" label-width="120px" prop="desc">
              <el-input
                v-model="form.desc"
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
              />
            </el-form-item>
            <el-form-item label="封面" label-width="120px">
              <UploadImage ref="uploadImage" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closeFn">取 消</el-button>
            <el-button type="primary" @click="confirmFn">确 定</el-button>
          </div>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getCategoriesList, addCategories, getCategoriesByID, editCategories, defCategories, getCategoriesCount } from '@/api/categories'
export default {
  data() {
    return {
      searchData: '',
      pagecount: 1,
      tableData: [], // 表格数据
      pagesize: 8, // 每页显示的数据
      title_contains: '', // 搜索框的数据
      page: 1, // 初始页码
      total: null, // 数据总数
      isShowDialog: false,
      // 表单数据
      form: {
        title: '',
        image: '',
        desc: ''
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '标题字符长度为1~10', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '描述不能为空', trigger: 'blur' },
          { min: 1, max: 200, message: '描述字符长度为1~200', trigger: 'blur' }
        ]
      }
    }
  },
  // 初始化页面渲染
  async created() {
    this.getCategoriesCount()
    this.getCategoriesList()
  },
  methods: {
    // 获取分类列表
    async getCategoriesList() {
      const res = await getCategoriesList({ _limit: this.pagesize, _start: (this.page - 1) * this.pagesize, title_contains: this.title_contains })
      console.log(res)
      this.tableData = res
    },
    // 翻页
    handleCurrentChange(page) {
      this.page = page
      this.getCategoriesList()
    },
    // 获取分类数量
    async getCategoriesCount() {
      this.total = await getCategoriesCount({ title_contains: this.title_contains })
    },
    // 搜索
    searchFn() {
      this.page = 1
      this.title_contains = this.searchData
      this.getCategoriesCount()
      this.getCategoriesList()
    },
    // 添加分类显示弹窗
    addFn() {
      this.isShowDialog = true
    },
    // 隐藏表单
    closeFn() {
      this.$refs.formData.resetFields()
      this.form = {
        title: '',
        image: '',
        desc: ''
      }
      this.$refs.uploadImage.fileList = []
      this.isShowDialog = false
    },
    // 编辑
    async editFn(id) {
      this.isShowDialog = true
      this.form = await getCategoriesByID(id)
      this.$refs.uploadImage.fileList.push({ url: this.form.image })
    },
    // 提交表单
    async confirmFn() {
      await this.$refs.formData.validate()
      // 编辑
      if (this.form.id) {
        if (this.$refs.uploadImage.fileList.length === 0) {
          return this.$message.error('请上传图片')
        }
        this.form.image = this.$refs.uploadImage.fileList[this.$refs.uploadImage.fileList.length - 1].url
        await editCategories(this.form)
        await this.getCategoriesList()
        this.getCategoriesCount()
        this.$message.success('编辑成功')
      } else {
        // 添加
        if (this.$refs.uploadImage.fileList.length === 0) {
          return this.$message.error('请上传图片')
        }
        this.form.image = this.$refs.uploadImage.fileList[this.$refs.uploadImage.fileList.length - 1].url
        await addCategories(this.form)
        await this.getCategoriesCount()
        this.page = Math.ceil(this.total / this.pagesize)
        await this.getCategoriesList()
        this.$message.success('添加成功')
      }
      this.closeFn()
    },
    // 删除分类
    delFn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await defCategories(id)
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
        this.getCategoriesCount()
        this.getCategoriesList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang='scss' >
.pagination{
  text-align: center;
}
.el-table td div{
  text-align: center;
}
</style>
